<?php
class Page_Be_Locale_Languages extends Page {
	function __construct() {
		$this->classTableObject = 'Db_Locale_Languages';
		$this->idTableObject = ($id = get('id', 'int')) ? $id : post('id', 'int');
		$this->actionsTableObject = array('ajaxEditAction');
		self::$TPL->appendJsFile('admin/languages');
		parent::__construct();
	}

	public function defaultAction(){
		perm('LANGUAGES_VIEW', '/');
		if ($userCanEdit = perm('LANGUAGES_EDIT')) {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '#add');
		}
		$allLanguages = Db_Locale_Languages::getLangs(false);
		self::$TPL->assign('allLanguages', $allLanguages);
		self::$TPL->assign('userCanEdit', $userCanEdit);
		self::$TPL->setBodyTemplate('list_languages');
		return array(
			'type' => 'display'
		);
	}

	public function ajaxEditAction(){
		$fieldName = post('fieldName', 'string');
		$value = post('value', 'string');
		$key = $value;
		if (perm('LANGUAGES_EDIT')) {
			if ($fieldName && $value && $this->tableObject && property_exists($this->tableObject, $fieldName)) {
				$this->tableObject->{$fieldName}=$value;
				if (!$this->tableObject->save(true)) {
					$key = $this->tableObject->objectArray->{$fieldName};
				}
			}
			$toReturn = '';
			if ('l_define' == $fieldName) {
				$toReturn = $key;
			} else if ($key) {
				$toReturn .= t(T_LANGUAGE_TITLE, $key);
				$toReturn .= '<input type="hidden" class="translation_key" value="' . $key . '"/>';
			}
		} else {
			$toReturn = '<div class="alert warning">' . t(T_ERROR_MESSAGE, 'access_denied') . '</div>';
		}
		return array(
			'type' => 'string',
			'content' => $toReturn
		);
	}

	public function ajaxChangeDefaultLanguageAction(){
		$class="";
		$message="";
		if (perm('LANGUAGES_EDIT')){
			if (($langId = post('defaultLangId', 'int')) && Db_Locale_Languages::setDefaultLanguage($langId)) {
				$class="success";
				$message= t(T_FORM_MSG, 'success');
			} else {
				$class="warning";
				$message=t(T_FORM_MSG, 'unknown_error_occurred');
			}
		} else {
			$class="warning";
			$message=t(T_ERROR_MESSAGE, 'access_denied');
		}
		return array(
			'type' => 'string',
			'content' => '<div class="alert ' . $class . '">' . $message . '</div>'
		);
	}

	public function ajaxSaveAction(){
		perm('LANGUAGES_EDIT', '/products/styles');
		$languages = array_filter(post('newLanguages', 'array'), function($item){
			return is_array($item) && 3 == count($item) && isset($item['l_define']) && strlen(trim($item['l_define']))
			&& isset($item['l_name_key']) && strlen(trim($item['l_name_key']))  && isset($item['l_short_name_key'])
			&& strlen(trim($item['l_short_name_key']));
		});
		if (count($languages) && Db_Locale_Languages::insertBatch($languages)) {
			$this->message= t(T_FORM_MSG, 'success');
		} else {
			$this->error = true;
			$this->message = t(T_FORM_MSG, 'unknown_error_occurred');
		}
		return array(
			'type' => 'redirect',
			'query' => false
		);
	}
}